﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Centido.Core.Dto;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Centido.Core.Test
{
    /// <summary>
    ///   Testing the data transfer object for table data.
    /// </summary>
    [TestClass]
    public class TableDataDtoTest : GenericDtoTest
    {
        /// <summary>
        ///   The current domain name.
        /// </summary>
        public const string DomainName = "FullAdminRights";

        /// <summary>
        ///   The current domain.
        /// </summary>
        private Domain _domain;

        /// <summary>
        ///   The table.
        /// </summary>
        private Table _table;

        /// <summary>
        /// Test initialiaze
        /// </summary>
        [TestInitialize]
        public void Initialize()
        {
            _domain = Domain.Build(DomainConfiguration.Load(DomainName));

            _domain.DeleteAll();

            _table = _domain.AddTable(StringProperty.RandomIdentifier());
        }

        /// <summary>
        /// Test clean up
        /// </summary>
        [TestCleanup]
        public void CleanUp()
        {
            _domain.DeleteAll();
        }


        /// <summary>
        ///   Retrieves the name of the data transfer object xml tag.
        /// </summary>
        /// <returns></returns>
        protected override string GetXmlTag()
        {
            return TableDataDto.XmlTag;
        }


        /// <summary>
        ///   Retrives the current xml schema version.
        /// </summary>
        /// <returns></returns>
        protected override string GetCurrentXmlSchemaVersion()
        {
            return TableDataDto.CurrentXmlSchemaVersion;
        }


        /// <summary>
        ///   Creates a new data transfer object.
        /// </summary>
        /// <returns></returns>
        protected override DataTransferObject CreateDto()
        {
            return new TableDataDto
            {
                TableName = StringProperty.RandomIdentifier()
            };
        }


        /// <summary>
        ///   Retrieves the list of data transfer object fields.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<DtoFieldInfo> GetFields()
        {
            yield return new DtoFieldInfo
            {
                Name = "TableName",
                XmlName = TableDataDto.TableNameAttribute,
                IsRequired = true,
                FieldType = DtoFieldType.String,
                SampleValue = StringProperty.RandomIdentifier(),
                HasTheSameNameAsCorrespondingObject = false,
                IsCopiedFromDto = false
            };
        }


        /// <summary>
        ///   Copies the properties of the data transfer object to the corresponding object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <returns>Returns the corresponding object after copying.</returns>
        protected override object CopyFrom(DataTransferObject dto)
        {
            return null;
        }


        /// <summary>
        ///   Creates a data transfer object from the correpsonding object.
        /// </summary>
        /// <param name="dto">The created data transfer object.</param>
        /// <param name="initialObject">The initial object.</param>
        protected override void CreateDtoFromObject(out DataTransferObject dto, out object initialObject)
        {
            dto = TableDataDto.CreateFrom(_table);
            initialObject = _table;
        }


        /// <summary>
        ///   Reading table data without read handler.
        /// </summary>
        [TestMethod]
        public void ReadingTableDataWithoutReadHandler()
        {
            // Creating a data table
            var xml = string.Format("<{0} {1}=\"{2}\">",
                TableDataDto.XmlTag,
                TableDataDto.TableNameAttribute,
                StringProperty.RandomIdentifier());

            // Creating a row list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\" />"
                + "</{7}></{8}>",
                TableDataDto.RowListTag,
                TableRowDataDto.XmlTag,
                TableRowDataDto.IdAttribute,
                Guid.NewGuid(),
                TableRowDataDto.XmlTag,
                TableRowDataDto.IdAttribute,
                Guid.NewGuid(),
                TableDataDto.RowListTag,
                TableDataDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var dataDto = new TableDataDto();

            dataDto.ReadXml(stream);
        }


        /// <summary>
        ///   Reading table data with the read handler.
        /// </summary>
        [TestMethod]
        public void ReadingTableDataWithReadHandler()
        {
            // Creating a data table
            var xml = string.Format("<{0} {1}=\"{2}\">",
                TableDataDto.XmlTag,
                TableDataDto.TableNameAttribute,
                StringProperty.RandomIdentifier());

            // Creating a row list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\" />"
                + "</{7}></{8}>",
                TableDataDto.RowListTag,
                TableRowDataDto.XmlTag,
                TableRowDataDto.IdAttribute,
                Guid.NewGuid(),
                TableRowDataDto.XmlTag,
                TableRowDataDto.IdAttribute,
                Guid.NewGuid(),
                TableDataDto.RowListTag,
                TableDataDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var columnList = new List<TableRowDataDto>();

            var dataDto = new TableDataDto { ReadHandler = (t, r) => columnList.Add(r) };

            dataDto.ReadXml(stream);

            Assert.AreEqual(columnList.Count, 2);
        }


        /// <summary>
        ///   Reading an empty row list.
        /// </summary>
        [TestMethod]
        public void ReadingEmptyRowList()
        {
            // Creating a data table
            var xml = string.Format("<{0} {1}=\"{2}\">",
                TableDataDto.XmlTag,
                TableDataDto.TableNameAttribute,
                StringProperty.RandomIdentifier());

            // Creating an empty row list
            xml += string.Format("<{0} /></{1}>",
                TableDataDto.RowListTag,
                TableDataDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var columnList = new List<TableRowDataDto>();

            var dataDto = new TableDataDto { ReadHandler = (t, r) => columnList.Add(r) };

            dataDto.ReadXml(stream);

            Assert.AreEqual(columnList.Count, 0);
        }


        /// <summary>
        ///   Reading and writing table data.
        /// </summary>
        [TestMethod]
        public void ReadingAndWritingTableData()
        {
            var tableDataDto = new TableDataDto
            {
                TableName = StringProperty.RandomIdentifier()
            };

            var firstRow = new TableRowDataDto
            {
                Id = Guid.NewGuid()
            };

            var secondRow = new TableRowDataDto
            {
                Id = Guid.NewGuid()
            };

            tableDataDto.WriteHandler = w =>
                {
                    firstRow.WriteXml(w);
                    secondRow.WriteXml(w);
                };

            var memoryStream = new MemoryStream();
            var writer = new XmlTextWriter(memoryStream, Encoding.UTF8);

            tableDataDto.WriteXml(writer);

            writer.Flush();

            memoryStream.Position = 0;
            var streamReader = new StreamReader(memoryStream);
            var xml = streamReader.ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(xml));

            memoryStream.Position = 0;
            var reader = new XmlTextReader(memoryStream);

            var rowList = new List<TableRowDataDto>();

            var dto = new TableDataDto { ReadHandler = (t, r) => rowList.Add(r) };

            dto.ReadXml(reader);

            Assert.AreEqual(rowList.Count, 2);
        }
    }
}
